﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;

using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Common;
using AKMII.DMRA.Service;
using AKMII.DMRA.Business.Service;
using AKMII.DMRA.Business.Rule;

namespace AKMII.DMRA.WindowService
{
    public partial class Service : ServiceBase
    {
        private ServiceHost commonServiceHost = null;

        public Service()
        {
            InitializeComponent();

            Constants.LogConfigFile = System.Configuration.ConfigurationSettings.AppSettings["logging.config"];
            Constants.ExcelReportPath = System.Configuration.ConfigurationSettings.AppSettings["ReportPath"];
        }

        protected override void OnStart(string[] args)
        {
            if (commonServiceHost != null)
            {
                commonServiceHost.Close();
            }

            try
            {
                Logger.Info("Starting common service.");

                commonServiceHost = new ServiceHost(typeof(CommonService));
                commonServiceHost.Opened += new EventHandler(ServiceHost_Opened);
                commonServiceHost.Open();
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in starting common service ", ex);
                throw new ApplicationException("Error in starting common service.");
            }
        }

        protected override void OnStop()
        {
            if (commonServiceHost != null)
            {
                Logger.Info("Closing common service.");

                commonServiceHost.Close();

                Logger.Info("Closed successfully.");

                commonServiceHost = null;
            }
        }

        private void ServiceHost_Opened(object sender, EventArgs e)
        {
            Logger.Info("Started successfully.");

            Mail mail = new Mail();
            mail.Subject = "Common Service is restarting";
            mail.Recipients = new List<string>() { "chris.li@akmii.com", "neil.yan@akmii.com" };

            SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
            mailService.Send(mail);
        }
    }
}
